package com.fz.song.feibao.web.controller.admin;


import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.fz.song.feibao.framework.common.R;
import com.fz.song.feibao.framework.common.enums.CodeEnum;
import com.fz.song.feibao.framework.common.enums.UserStateEnum;
import com.fz.song.feibao.web.entity.Admin;
import com.fz.song.feibao.framework.exceptions.ServerException;
import com.fz.song.feibao.web.service.IAdminService;
import com.fz.song.feibao.web.entity.vo.login.req.AdminLoginReqVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;


@Api(tags = "管理员登录-登出控制器")
@Slf4j
@RestController
@RequestMapping("admin")
public class AdminLoginController {


    @Value("${feibao.admin.user-key}")
    private String userKey;

    @Autowired
    private IAdminService adminService;

    @ApiOperation("管理员登录系统")
    @PostMapping("login")
    public R login(@Valid @RequestBody AdminLoginReqVO req) {
        String userName = req.getUsername();
        Admin admin = adminService.getByUsername(userName);
        if (admin == null) {
            throw new ServerException(CodeEnum.USERNAME_OR_PWD_ERROR);
        }
        Integer state = admin.getState();
        if (UserStateEnum.LOCK.getState() == state) {
            throw new ServerException(CodeEnum.USER_ABNORMAL);
        }
        String password = admin.getPassword();
        String pwd = req.getPassword();
        String pwdEn = SaSecureUtil.md5BySalt(pwd, userKey);
        if (!password.equals(pwdEn)) {
            throw new ServerException(CodeEnum.USERNAME_OR_PWD_ERROR);
        }
        Integer id = admin.getId();
        StpUtil.login(id);
        SaTokenInfo token = StpUtil.getTokenInfo();
        HashMap<String, String> map = new HashMap<>();
        map.put("tokenName", token.getTokenName());
        map.put("tokenValue", token.getTokenValue());
        return R.ok("登录成功", map);
    }

    @ApiOperation("管理员退出系统")
    @GetMapping("logout")
    @SaCheckLogin
    public R logout() {
        StpUtil.logout();
        return R.ok("退出成功");
    }

}
